<script setup>
import { watch } from 'vue'
import { SWITCH } from '@/constant/index.js'
import { useCommonStore } from '@/stores'
const commonStore = useCommonStore()

const props = defineProps({
  // 照片数组
  images: {
    type: Object,
    default: []
  },
  // 当前照片
  currentIndex: {
    type: Number,
    default: 0
  },
  // 是否显示
  isOpen: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['change'])

// 锁定滚动条
watch(
  () => props.isOpen,
  (newValue) => {
    if (newValue) {
      document.body.style.overflow = 'hidden'
      document.body.style.width = 'calc(100% - 17px)' // 避免因为消失滚动条造成页面抖动
    } else {
      document.body.style.overflow = 'auto'
      document.body.style.width = '100%' // 避免因为消失滚动条造成页面抖动
    }
  }
)

// 切换图片
const onSwitchImg = (flag) => {
  if (SWITCH.PREV === flag) {
    emit('change', props.currentIndex - 1)
  } else {
    emit('change', props.currentIndex + 1)
  }
}
</script>

<template>
  <Transition name="fade_img">
    <div class="image-wrap" v-show="isOpen" :style="{ top: commonStore.isShowHead ? '52px' : '0' }">
      <div class="bg"></div>
      <div class="image">
        <div class="switch" v-if="images.length > 1" @click="onSwitchImg(SWITCH.PREV)">
          <svg-icon icon-name="xiangzuo1" />
        </div>
        <img class="view-img" :src="images[currentIndex]?.img_url" />
        <div class="switch" v-if="images.length > 1" @click="onSwitchImg(SWITCH.NEXT)">
          <svg-icon icon-name="xiangyou1" />
        </div>
      </div>
    </div>
  </Transition>
</template>

<style lang="scss" scoped>
.image-wrap {
  position: fixed;
  top: 52px;
  left: 0;
  bottom: 0;
  right: 360px;
  transition: all 0.3s;
}
.bg {
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background-color: var(--img-view-bg);
  backdrop-filter: blur(10px);
  transition: var(--tr);
}
.image {
  height: 100%;
  display: flex;
  padding: 0 20px;
  .switch {
    align-self: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background-color: var(--gray-text-2);
    color: var(--gray-text-3);
    font-size: 20px;
    opacity: 0.5;
    transition: var(--tr);
    user-select: none;
    cursor: pointer;
    &:hover {
      opacity: 1;
    }
  }
  .view-img {
    margin: 20px;
    flex: 1;
    overflow: hidden;
    object-fit: contain;
  }
}
/* 进入起点&离开终点 */
.fade_img-enter-from,
.fade_img-leave-to {
  opacity: 0;
}
.fade_img-enter-active {
  transition: opacity 0.2s ease-out;
}
.fade_img-leave-active {
  transition: opacity 0.2s ease-in;
}
/* 离开起点&进入终点 */
.fade_img-enter-to,
.fade_img-leave-from {
  opacity: 1;
}
</style>
